using System;
using System.Collections.Generic;
using System.Linq;

namespace Atomic.Libraries.Mathematics.RandomNumbers
{
	public static class RandomShuffle
	{
		public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, IRandomGenerator randomGenerator)
		{
			// http://stackoverflow.com/a/1287572
		    T[] elements = source.ToArray();
		    for (int i = elements.Length - 1; i >= 0; i--)
		    {
		        // Swap element "i" with a random earlier element it (or itself)
		        // ... except we don't really need to swap it fully, as we can
		        // return it immediately, and afterwards it's irrelevant.
		        int k = randomGenerator.Next(i + 1);
		        yield return elements[k];
		        elements[k] = elements[i];
		    }
		}
	}
}
